/**
 * @author مۇختەرجان مەخمۇت (mutearjan mahmood)
 * @email yeganaaa@163.com`
 * @create date 2020-08-31 03:34:16
 * @modify date 2020-08-31 03:34:16
 * @desc [description]
*/

import { IRpcServerHost, ServerHostEvents } from "./RpcServer"

/**
 * Group multiple server hosts
 * @remarks
 * This is very useful when this server should accept client connections on different communication environment such as WebSocket, TcpSocket and others.
 * Rpc server can be accept multiple server host connection at the same time.
 */
export class RpcServerHostGroup implements IRpcServerHost<void> {
    backend: void = null!
    handler: ServerHostEvents = null!
    public constructor(private hosts: IRpcServerHost<any>[]) { }
    public async prepare(eventHandler: ServerHostEvents): Promise<void> {
        this.handler = eventHandler
        let preparedCount = 0, shutdownCount = 0
        const eventHandlerForChildHosts = new ServerHostEvents(
            async () => {
                preparedCount++
                if (preparedCount == this.hosts.length) await this.handler.onReady()
            },
            async bridge => await this.handler.onClientConnected(bridge),
            async error => await this.handler.onError(error),
            async () => {
                shutdownCount++
                if (shutdownCount == this.hosts.length) await this.shutdown()
            }
        )
        await Promise.all(this.hosts.map(host => host.prepare(eventHandlerForChildHosts)))
    }
    public async launch(): Promise<void> {
        await Promise.all(this.hosts.map(host => host.launch()))
    }
    public async shutdown(): Promise<void> {
        await Promise.all(this.hosts.map(host => host.shutdown()))
    }
}